package main

import (
	"errors"
	"iot-base/common/cache"
	"iot-base/common/eventtype"
	"iot-base/common/notify"
	"net"
	"strconv"
	"strings"
	"time"

	"fmt"
)

func GetUPSTask(id string, thing *cache.ThingInfo, v interface{}, round int64) (interface{}, error) {
	ip := thing.GetThingParam("IP", "")
	if ip == "" {
		fmt.Println("ip is nil")
		return nil, errors.New("ip is nil")
	}
	port := thing.GetThingParam("Port", "")
	if port == "" {
		fmt.Println("port is nil")
		return nil, errors.New("port is nil")
	}
	conn, err := net.DialTimeout("tcp", ip+":"+port, 3*time.Second)
	if err != nil {
		fmt.Println("connect " + ip + " err:" + err.Error())
		return nil, errors.New("connect " + ip + " err:" + err.Error())
	}
	_, err = conn.Write([]byte{0x51, 0x31, 0x0d})
	fmt.Println(string([]byte{0x51, 0x31, 0x0d}))
	if err != nil {
		fmt.Println("conn write err:" + err.Error())
		return nil, errors.New("conn write err:" + err.Error())
	}
	res := make([]byte, 1024)
	n, err := conn.Read(res)
	if err != nil || n == 0 {
		fmt.Println("conn read err" + err.Error())
		return nil, errors.New("conn read err" + err.Error())
	}
	tmp := string(res[:n])
	fmt.Println("res:", string(res[:n]))
	result := strings.Split(tmp, " ")
	now := time.Now().Unix()
	if len(result) == 8 {
		notify.RawData(id, "input_voltage", "", 0, result[0][1:], now, now)
		notify.RawData(id, "discharge", "", 0, result[1], now, now)
		notify.RawData(id, "output_voltage", "", 0, result[2], now, now)
		notify.RawData(id, "loader", "", 0, result[3], now, now)
		notify.RawData(id, "input_frequency", "", 0, result[4], now, now)
		notify.RawData(id, "unit_voltage", "", 0, result[5], now, now)
		notify.RawData(id, "temperature", "", 0, result[6], now, now)
		notify.RawData(id, "alarmVoltage", "", 0, string(result[7][7]), now, now)
		notify.RawData(id, "UPS_broke", "", 0, string(result[7][4]), now, now)
		unit_voltage, _ := strconv.ParseFloat(result[5], 32)
		notify.RawData(id, "power", "", 0, 48.0*unit_voltage, now, now)
		var side bool
		if result[7][5] == '1' {
			side = false
		} else if result[7][5] == '0' && result[7][7] == '1' {
			side = true
		}
		notify.RawData(id, "side", "", 0, side, now, now)
		AlarmArr := []string{
			"test",
			"offline",
			"UPS_broke",
			"output_side",
			"battery_low_Voltage",
			"alarmVoltage",
		}
		fmt.Println(result[7])
		for i := 2; i < len(result[7])-1; i++ {
			var flag string
			if result[7][i] == 1 {
				flag = "BEGIN"
			} else if result[7][i] == 0 {
				flag = "END"
			}
			alarm := eventtype.Alarm{
				Flag: flag,
			}
			alarm.TID = id
			alarm.Time = time.Now().Unix()
			alarm.Mindex = 0
			alarm.AlarmID = AlarmArr[i-2]
			notify.RawAlarm(&alarm)
		}
		return nil, nil
	} else {
		fmt.Println("result count is err:" + fmt.Sprint(len(result)))
		return nil, errors.New("result count is err:" + fmt.Sprint(len(result)))
	}
}
